package pl.jtb.ctl.tabory.ui.se.ui;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.Section;

import pl.jtb.ctl.tabory.dao.api.services.IUserService;
import pl.jtb.ctl.tabory.dao.data.vo.UserVO;
import pl.jtb.ctl.tabory.dao.impl.mybatis.servicemanager.ServiceManager;
import pl.jtb.ctl.tabory.ui.editors.AbstractMasterDetailSection;
import pl.jtb.ctl.tabory.ui.editors.EditorStateSL;
import pl.jtb.ctl.tabory.ui.se.osgi.Activator;
import pl.jtb.ctl.tabory.ui.se.selection.UserSelection;
import pl.jtb.ctl.tabory.ui.selection.ISelectionListener;

public class SecurityEditor extends AbstractMasterDetailSection<UserSelection, SecurityMasterSectionPart, SecurityDetailSectionPart> {

    public static final String ID = "pl.jtb.ctl.tabory.ui.se.ui.SecurityEditor";

    private static final Logger logger = Logger.getLogger(SecurityEditor.class);

    public SecurityEditor() throws Exception {
        super();
    }

    @Override
    protected SecurityMasterSectionPart getMasterSection(Form parentForm) {
        SecurityMasterSectionPart sectionPart = new SecurityMasterSectionPart(parentForm.getBody(), formToolkit, Section.TITLE_BAR, Activator.getMessage("editor.master.title"), true, true);
        sectionPart.setSelection(selection);
        return sectionPart;
    }

    @Override
    protected SecurityDetailSectionPart getDetailSection(Form parentForm) {
        SecurityDetailSectionPart sectionPart = new SecurityDetailSectionPart(parentForm.getBody(), formToolkit, Section.TITLE_BAR, Activator.getMessage("editor.detail.title"));
        sectionPart.setSelection(selection);
        return sectionPart;
    }

    @Override
    protected void postInitGui(Composite parent) {
        masterSectionPart.addSelectionListener(new ISelectionListener<UserSelection>() {
            @Override
            public void selectionChanged(final UserSelection selection) {
                logger.debug("Selection changed");
                BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
                    @Override
                    public void run() {
                        EditorStateSL editorStateSL = selection.getEditorStateSL();
                        if (editorStateSL.equals(EditorStateSL.CLEAN)) {
                            setDirty(false);
                        } else {
                            setDirty(true);
                        }
                        masterSectionPart.setSelection(selection);
                        detailSectionPart.setSelection(selection);
                    }
                });
            }
        });
    }

    @Override
    protected void doSave() throws Exception {
        IUserService userService = ServiceManager.getInstance().getUserService();
        UserSelection saveSelection = detailSectionPart.getSelection();
        UserVO selectedUser = saveSelection.getSelectedUser();
        if (selectedUser.getId() == null) {
            UserVO user = userService.getUser(selectedUser.getUserLogon());
            if (user != null) {
                MessageDialog.openError(getSite().getShell(), Activator.getMessage("validation.unique.title"), Activator.getMessage("validation.unique.message"));
                return;
            }
        }
        Date dateValidFrom = selectedUser.getDateValidFrom();
        Date dateValidUntil = selectedUser.getDateValidUntil();
        if (dateValidFrom != null && dateValidUntil != null) {
            if (!dateValidFrom.before(dateValidUntil)) {
                Exception ex = new Exception(Activator.getMessage("exceptions.validate.date"));
                throw ex;
            }
        }
        userService.saveUpdateUser(selectedUser);
        selection = initSelection();
        masterSectionPart.setSelection(selection);
        detailSectionPart.setSelection(selection);
        setDirty(false);
    }

    @Override
    protected void doCancel() throws Exception {
        selection.setSelectedUser(null);
        selection.setEditorStateSL(EditorStateSL.CLEAN);
        masterSectionPart.setSelection(selection);
        detailSectionPart.setSelection(selection);
        setDirty(false);
    }

    @Override
    protected UserSelection initSelection() throws Exception {
        logger.debug("Creating selection");
        UserSelection selection = new UserSelection();
        IUserService userService = ServiceManager.getInstance().getUserService();
        List<UserVO> listAllUsers = userService.getAllUsers();
        selection.setListAllUsers(listAllUsers);
        selection.setEditorStateSL(EditorStateSL.CLEAN);
        logger.debug("Selection created");
        return selection;
    }

    @Override
    public void setFocus() {
        setDirty(true);
        editorCancelAction.run();
    }

}
